helper='
look README.md
'

rootpath=$(dirname $0)
binpath=$rootpath/FlameGraph
if [ ! -d $binpath ]; then
    tar -zxf $rootpath/FlameGraph.tar.gz -C $rootpath
fi

target=""
catch_time=30
mode="--call-graph dwarf"
name=''
output_path=$rootpath

while [ $# -gt 0 ]; do
    case "$1" in
        -p) target="-p $2"    && shift 1 ;;
        -t) target="-t $2"    && shift 1 ;;
        -T) catch_time=$2     && shift 1 ;;
        -n) name="_$2"        && shift 1 ;;
        -o) output_path="$2"  && shift 1 ;;
        -u) mode='' ;;
        *)  echo $helper && exit 1 ;;
    esac
    shift 1
done

if [ "$target" = "" ]; then
    procid=`ps -ef|grep gaussdb|grep -v grep|awk '{print $2}'`
    target="-p $procid"
fi


pid=`date '+%Y-%m-%d-%H-%M'`
datafile=$rootpath/perf_data_${pid}
foldfile=$rootpath/out_${pid}.perf-folded
svgfile=$output_path/perf_fire_${pid}${name}.svg

perf record -g -F 99 $mode $target -o $datafile sleep $catch_time
perf script -i $datafile | $binpath/stackcollapse-perf.pl > $foldfile
cat $foldfile | $binpath/flamegraph.pl > $svgfile

rm $datafile  $foldfile perf.data -fr

echo $svgfile